﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using TuringCup;
namespace GameServer
{
    class AI_Container
    {
        /// <summary>
        /// AI的阵营
        /// </summary>
        public int side;
        Object dllobj = null;
        Type dlltype = null;
        System.Reflection.MethodInfo dllmethod = null;
        /// <summary>
        /// 队伍名
        /// </summary>
        public String team_name = "UnDefined";
        /// <summary>
        /// 根据dll的路径加载dll格式的AI程序
        /// </summary>
        /// <param name="path">包含AI程序的dll文件的路径</param>
        public void LoadDll(String path)
        {
            try
            {
                System.Reflection.Assembly AppAssembly = System.Reflection.Assembly.LoadFile(path);
                dlltype = AppAssembly.GetType("TuringCupAI.GameAI");
                dllmethod = dlltype.GetMethod("main");
                InitAI();
            }
            catch (Exception)
            {
                Console.WriteLine("Load AI " + path + "failed");
                throw;
            }
        }
        /// <summary>
        /// 初始化AI,获取队伍名,检测可能的AI加载错误
        /// </summary>
        void InitAI()
        {
            try
            {
                dllobj = Activator.CreateInstance(dlltype);
                team_name = (String)dlltype.GetField("teamname",BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static).GetValue(dllobj);
                System.Reflection.MethodInfo init_method = dlltype.GetMethod("init");
                object[] parameter = new object[1];
                parameter[0] = side;
                init_method.Invoke(dllobj, parameter);
            }
            catch (Exception)
            {
                Console.WriteLine("AI " + side + "init failed");
                throw;
            }

        }
        /// <summary>
        /// AI执行接口
        /// </summary>
        /// <param name="state">战场状态序列化后的JSON字符串</param>
        /// <returns>返回AI想要执行的指令</returns>
        public AI_Commands RunAI(String state)
        {
            //未加载AI时返回空
            if (dllmethod == null)
                return new AI_Commands();
            object[] parameter = new object[1];
            parameter[0] = state;
            String result = (String)dllmethod.Invoke(dllobj, parameter);
            return AI_Commands.Load(result);
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="side">规定AI的阵营</param>
        public AI_Container(int side)
        {
            this.side = side;
        }
    }
}
